package com.wjs.juc.Future;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * join()和get()的区别
 * join编译时不会检查异常,get编译时会检查异常
 */
public class CompletableFutureMallDemo {
    public static List<NetMall> list;
    static {
        list= Arrays.asList(new NetMall("JD"),
                            new NetMall("TB"),
                            new NetMall("PDD"));
    }
    public static List<String> getPrice(String produceName){
        List<String> result = CompletableFutureMallDemo.list.stream().map(m -> {
            return String.format(produceName + " in %s is %.2f", m.getNetMallName(), m.calPrice(produceName));
        }).collect(Collectors.toList());
        return result;
    }
    public static List<String> getPriceWithCompletable(String produceName){
        List<String> result = list.stream().map(m -> CompletableFuture.supplyAsync(() -> {
            return String.format(produceName + " in %s is %.2f", m.getNetMallName(), m.calPrice(produceName));
        })).collect(Collectors.toList()).stream().map(c -> c.join()).collect(Collectors.toList());
        return result;
    }
    public static void main(String[] args) {
    long start=System.currentTimeMillis();
        List<String> mysql = getPrice("mysql");
        for (String s : mysql) {
            System.out.println(s);
        }
        long end=System.currentTimeMillis();
        System.out.println("耗时"+(end-start)+"ms");

        System.out.println("_________________________________________");
        long start1=System.currentTimeMillis();
        List<String> mysqls = getPriceWithCompletable("mysql");
        for (String s : mysqls) {
            System.out.println(s);
        }
        long end1=System.currentTimeMillis();
        System.out.println("耗时"+(end1-start1)+"ms");
    }
}
@AllArgsConstructor
class NetMall{
    @Getter
    private String netMallName;

    public void setNetMallName(String netMallName) {
        this.netMallName = netMallName;
    }

    public double calPrice(String produceName){
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace();}
        return new Random().nextDouble()+produceName.charAt(0);
    }
}
